package com.undsf.comikamij.kukudm;

import com.undsf.comikamij.core.BaseCrawler;
import com.undsf.comikamij.core.entities.Chapter;
import com.undsf.comikamij.core.entities.Comic;
import com.undsf.comikamij.core.entities.Page;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Arathi on 2017/4/7.
 */
public class KukuCrawler extends BaseCrawler {
    private static Logger logger = LogManager.getLogger(KukuCrawler.class);
    private static Pattern PATTERN_CHAPTER = Pattern.compile(".*/([\\w\\d]*)/([\\w\\d]*)/.*\\.htm");
    private static Pattern PATTERN_IMG_SRC = Pattern.compile("<IMG SRC='\"\\+(m\\d{6}d)\\+\"(.*)'><span");
    private static Pattern PATTERN_PAGE_AMOUNT = Pattern.compile("\\| 共(\\d+)页 \\|");

    private static String m200911d = "http://n.1whour.com/";
    private static String m201001d = "http://n.1whour.com/";
    private static String m201304d = "http://n.1whour.com/";

    public static final String DOMAIN = "comic.kukudm.com";
    public static final String URL_INDEX = "http://" + DOMAIN;

    @Override
    public List<Comic> crawlIndex() {
        List<Comic> comics = new ArrayList<>();
        return comics;
    }

    @Override
    public List<Chapter> crawlTOC(String id) {
        List<Chapter> chapters = new ArrayList<>();
        String tocUrl = "http://" + DOMAIN + "/comiclist/" + id + "/";
        try {
            String html = client.get(tocUrl);
            Document doc = Jsoup.parse(html);
            String selector = "dl#comiclistn dd";
            Elements dds = doc.select(selector);
            for (Element dd : dds) {
                Chapter chapter = new Chapter();
                Element chapterLink = dd.select("a").first();
                chapter.name = chapterLink.text();

                // Element chapterLinkMirror = dd.select("a").last();

                String href = chapterLink.attr("href");
                Matcher matcher = PATTERN_CHAPTER.matcher(href);
                if (matcher.find()) {
                    chapter.id = matcher.group(2);
                    chapter.referrer = "http://" + DOMAIN + href;
                }
                else {
                    continue;
                }

                chapters.add(chapter);
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        return chapters;
    }

    @Override
    public List<Page> crawlPagesOfChapter(String comic, String chapter) {
        List<Page> pages = new ArrayList<>();
        int pageNumber = 0;
        Page page = null;
        do {
            page = crawlPage(comic, chapter, ++pageNumber);
            if (page == null) continue;
            pages.add(page);
        }
        while (!page.lastPage);
        return pages;
    }

    public Page crawlPage(String comic, String chapter, int pageNumber) {
        String tocUrl = "http://" + DOMAIN + "/comiclist/" + comic + "/" + chapter + "/" + pageNumber + ".htm";
        try {
            System.out.println(tocUrl);
            String html = client.get(tocUrl);
            if (html == null) return null;

            Matcher matcher = PATTERN_IMG_SRC.matcher(html);
            if (matcher.find()) {
                Page page = new Page();
                // String varName = matcher.group(1);
                String url = matcher.group(2);
                String picUrl = m201304d + url;

                page.number = pageNumber;
                page.referrer = tocUrl;
                page.url = picUrl;

                // 检测是否为最后一页
                matcher = PATTERN_PAGE_AMOUNT.matcher(html);
                if (matcher.find()) {
                    int pageAmount = Integer.parseInt(matcher.group(1));
                    page.lastPage = (pageAmount == pageNumber);
                }
                return page;
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
